package com.example.notering;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ViewActivity extends Activity {
	String currentAc;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view);
		//获得当前activity名称
		TextView v = (TextView)findViewById(R.id.view_title);
		currentAc = getRunningActivityName().subSequence(21, getRunningActivityName().length()).toString();
		v.setText(currentAc);
		
		//获得所监听应用程序的所有activity
		EditText v1 = (EditText)findViewById(R.id.view_content);
        List<String> activities = getActivitiesClass(this, "com.mayshe.lepai");
        for(int i=0;i<activities.size();i++){
    		v1.append(activities.get(i).toString());
        }
        
        //启动其他应用程序
        Button b1 = (Button)findViewById(R.id.view_delete);
        b1.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				ComponentName componetName = new ComponentName("com.mayshe.lepai","com.mayshe.lepai.activity.SplashActivity");  
				Intent intent = new Intent();  
	            intent.setComponent(componetName);
	            startActivity(intent);  
			}});
        //
//        while(true){
//        	if(currentAc.equals(getRunningActivityName().subSequence(21, getRunningActivityName().length())))
//        		v1.append(getRunningActivityName().subSequence(21, getRunningActivityName().length())+""+System.currentTimeMillis()+"\n");
//        }
        
        v.setText(getStartTimeFromLogcat());
	}

	private String getRunningActivityName(){     
		Log.e("t1", System.currentTimeMillis()+"");
        ActivityManager activityManager=(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);  
        String runningActivity=activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
        Log.e("t2", System.currentTimeMillis()+"");
        return runningActivity;                 
	}
	
	public final static List<String> getActivitiesClass(Context context, String packageName){
        
        List<String> returnClassList = new ArrayList<String>();
        PackageInfo packageInfo;
        ActivityInfo[] activityInfo;
		try {
			packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
			activityInfo = packageInfo.activities;
			if(packageInfo.activities!=null){
	            Log.d("", "Found "+activityInfo.length +" activity in the AndrodiManifest.xml");
			}
			for(ActivityInfo ai: packageInfo.activities){
	            returnClassList.add(ai.name.substring(26)+"\n");
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
        return returnClassList;
	}
	
	private String getStartTimeFromLogcat() {
    	String startTime = null;
        try {
            String logcatCommand = "logcat -v time -d ActivityManager:I *:S";
            Process process = Runtime.getRuntime().exec(logcatCommand);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder strBuilder = new StringBuilder();
            String line = "";

            while ((line = bufferedReader.readLine()) != null) {
                strBuilder.append(line);
                strBuilder.append("\r\n");
                String regex = ".*Displayed.*" + "com.mayshe.lepai.activity.SplashActivity" + ".*\\+(.*)ms.*";
                Log.d("my logs", regex);
                if (line.matches(regex)) {
                    Log.w("my logs", line);
                    if (line.contains("total")) {
                        line = line.substring(0, line.indexOf("total"));
                    }
                    startTime = line.substring(line.lastIndexOf("+") + 1, line.lastIndexOf("ms") + 2);
                    Log.i("启动时间：" ,startTime+"");
                    break;
                }
            }
        } catch (IOException e) {
        }
		return startTime;
    }
}
